import {track, trigger} from './effect.js'

function createReactive(obj, isShallow =  false, isReadonly = false) {
  return new Proxy(obj, {
    get(target, key, receiver) {
      const res = Reflect.get(target, key, receiver)
      if(!isReadonly) {
        track(target, key)
      }
      if(typeof res === 'object' && res !== null) {
        return isReadonly ?  readonly : reactive(res)
      }
      if(isShallow) {
        return res
      }
      return res
    },
    set(target, key, newValue, receiver) {  
      if(isReadonly) {
        console.warn(`属性 ${key} 是只读的`)
        return true
      }
      const res = Reflect.set(target, key, newValue, receiver)
      trigger(target, key)
      return res
    }
  })
}

export function reactive(obj) {
  return createReactive(obj)
}
export function readonly(obj) {
  return createReactive(obj, false, true)
}
export function shallowReactive(obj) {
  return createReactive(obj, true, false)
}

export function shallowReadonly(obj) {
  return createReactive(obj, true, true)
}
